#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include "humanseg_c_wrap.h"
#include "base_exception_wrap.h"

using namespace cv;


int main(int ac, char *av[])
{
 
    humanseg_ref_t h_seg;
    const char  *img_path;

    char *ptmp;
    int model_type;

    set_default_exception_handler();

    if (ac != 2){
        printf("usage : %s model_type \n all model types: \n", av[0]);
        humanseg_print_all_models();
        return 0;
    }
 
    model_type = strtol(av[1], &ptmp, 10);


    img_path = av[2];

    h_seg = humanseg_create(model_type,  1, 0);
    if (!h_seg){
        printf("load models failed \n");
        return -1;
    }


    VideoCapture capture(0);

    capture.set(CAP_PROP_FRAME_WIDTH, 960);  
    capture.set(CAP_PROP_FRAME_HEIGHT,540); 


    cv::Mat img_bg = cv::imread("../data/bg0.jpg");
    cv::Mat img_bg1;
    cv::namedWindow("mask-blend", cv::WINDOW_AUTOSIZE);
    
    cv::resize(img_bg, img_bg1, cv::Size(960, 540));

    while(1){
        Mat img, img_rgb;  

        
        //1  capture on frame 
        capture>>img;  

        if (img.cols != img_bg1.cols || img.rows != img_bg1.rows){
            cv::resize(img_bg, img_bg1, cv::Size(img.cols, img.rows));
        }

        if (img.cols < 1){
            printf(" invalid image <%s>\n", img_path);
            return -1;
        }
        /// to RGB
        cv::cvtColor(img, img_rgb, cv::COLOR_BGR2RGB);



        // 2 detect 
        cv::Mat alpha(img_rgb.rows, img_rgb.cols, CV_8UC1);

        humanseg_detect_rgb24(h_seg, img_rgb.cols, img_rgb.rows, (unsigned char *)img_rgb.data, (int)img_rgb.step[0], (unsigned char *)alpha.data, (int)alpha.step[0]);

        // 3 bg replace 
        cv::Mat img_mix(img.rows, img.cols, CV_8UC3);

         humanseg_bg_replace_rgb24(h_seg, img.cols, img.rows, (unsigned char *)img.data, (int)img.step[0], 
            (unsigned char *)img_bg1.data, (int)img_bg1.step[0], img_mix.data, (int)img_mix.step[0],
            (unsigned char *)alpha.data, (int)alpha.step[0]
        );


        cv::imshow("mask-blend", img_mix);
        cv::waitKey(1);

    }

 
    humanseg_destroy(h_seg);

    return 0;
}
